package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.Result;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /*
    分页查询分类的数据
    */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize) {
        log.info("page={},pageSize={},name={}", page, pageSize);
        Page pageinfo = new Page(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.orderByDesc(Category::getSort);
        categoryService.page(pageinfo, queryWrapper);
        return Result.success(pageinfo);
    }
    /*
    根据条件查询分类
     */
    @GetMapping("/list")
    public Result<List<Category>> selectlist(Category category){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return Result.success(list);
    }
    /*
    新增分类
    */
    @PostMapping
    public Result<String> save(@RequestBody Category category){
        log.info("catory{}",category);
        categoryService.save(category);
        return Result.success("新增分类信息成功！");

    }
    /*
    修改分类状态
    */
    @PutMapping
    public Result<String> update(@RequestBody Category category){
        log.info(category.toString());
        categoryService.updateById(category);
        return Result.success("分类信息修改成功！");
    }
    /*
    删除分类
    */
    @DeleteMapping
    public Result<String> delete(Long id){
        log.info("根据id删除分类....");
        categoryService.remove(id);
        return Result.success("分类删除成功！");
    }
}
